﻿using log4net;
using OA.BLL;
using OA.Model;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;

using System.Data.SqlClient;
using System.Linq;
using System.Linq.Expressions;
using System.Web;

using System.Text;
using OA.Core;
using System.Reflection;
using OA.Web.Controllers;
using OA.Web.Code;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Primitives;
using OA.Core.Helper;
using OA.Model.DB;
using Microsoft.AspNetCore.Mvc;
using OA.Web.Attribute;
using Microsoft.EntityFrameworkCore;
using OA.Core.Oss;

namespace OA.Web.Areas.Member.Controllers
{
    [Area("Member")]
    [MemberFilter]
    public class BaseMemberController : BaseController
    {         
        public Employee Info { get; set; }
        public int DepartmentID = 142;
        public List<MenuInfo> MyMenus = new List<MenuInfo>();
        public List<string> CurrentPermissionCodes = new List<string>();
        public List<string> Codes { get; set; }
        private readonly ICookie _cookie;
        private readonly IMemoryCache _cache;
        public bool IsDepartmentHead { get; set; }
        public string Prompt { get; set; }
        public string Signature { get; set; }
        /// <summary>
        /// 当期用户岗位
        /// </summary>
        public List<int> PositionIDs { get; set; }

        public BaseMemberController(IHttpContextAccessor accessor, ICookie cookie, IMemoryCache cache) : base(accessor, cookie, cache)
        {
            _cookie = cookie;
            _cache = cache;
            StringValues messaes;
            accessor.HttpContext.Request.Query.TryGetValue("msg",out messaes);
            if(messaes.Count>0)
            {
                this.Prompt = accessor.HttpContext.Request.Query["msg"];
            }
            string memberIDStrMM = cookie.GetCookies(CookieHelper.UserID);
            if (string.IsNullOrWhiteSpace(memberIDStrMM))
            {
                return;
            }

            string memberIDStr = memberIDStrMM.FromBase62<string>();
            if (string.IsNullOrWhiteSpace(memberIDStr))
            {
                return;
            }
            Info = this.dbContextFactory.DbContext.Employee.Where(m => m.EmpID == memberIDStr).FirstOrDefault();
            PositionIDs = this.dbContextFactory.DbContext.EmployeePosition.Where(m => m.EmpID == memberIDStr && m.Status != -1).Select(m => m.PositionID).ToList();
            if (Info == null) return;
            CallContext.SetData("MemberInfo", Info);
            EmpID = Info.EmpID;           
            UserID = Info.ID;
            this.Signature = Info.EmpID.ToBase62();
            var listPermissionGroupID = this.dbContextFactory.DbContext.UserPermissionGroup.Where(m => m.EmpID == EmpID).Select(m => m.PermissionGroupID).ToList();
            List<string> permissionCodes = new List<string>();
            if (listPermissionGroupID.Count>0)
            {
                List<PermissionGroup> listPermissionGroup = this.dbContextFactory.DbContext.PermissionGroup.Where(m => listPermissionGroupID.Contains(m.ID)).ToList();
                foreach (PermissionGroup itemPermissionGroup in listPermissionGroup)
                {
                    List<string> temps = JsonHelper.DeserializeList<string>(itemPermissionGroup.PermissionContext).Where(m => !string.IsNullOrWhiteSpace(m)).ToList();
                    permissionCodes = permissionCodes.Union(temps).ToList();
                }
            }
            
            permissionCodes.Add("000000");
            permissionCodes = permissionCodes.Distinct().ToList();

            this.CurrentPermissionCodes.AddRange(permissionCodes.Select(m=>m).ToList());

            for (int i=0;i< permissionCodes.Count; i++)
            {
                if(permissionCodes[i].Length==9)
                {
                    permissionCodes.Add(permissionCodes[i].Substring(0, 6));
                }
            }

            permissionCodes = permissionCodes.Distinct().ToList();

            
            this.MyMenus = this.GetMenuInfos();
            this.Codes = permissionCodes;
            foreach (var item in this.MyMenus)
            {
                if(permissionCodes.Contains(item.c))
                {
                    item.s = true;
                }
            }
            var departmentHeadID = this.dbContextFactory.DbContext.Department.Where(m => PositionIDs.Contains(m.LeaderPositionID) || PositionIDs.Contains(m.LeaderPositionID2??0)).Select(m => m.ID).FirstOrDefault();
            if(departmentHeadID>0)
            {
                this.IsDepartmentHead = true;
            }
            else
            {
                this.IsDepartmentHead = false;
            }
        }

        public ContentResult FinshAdd()
        {
            return Content("<script>window.parent.FinshAdd();</script>", "text/html");
        }

        public ContentResult FinshEdit()
        {
            return Content("<script>window.parent.FinshEdit();</script>", "text/html");
        }

        public ContentResult FinshOther(string msg)
        {
            return Content($"<script>window.parent.FinshOther('{msg}');</script>", "text/html");
        }

        public ContentResult FinshOther2(string msg)
        {
            return Content($"<script>window.parent.FinshOther2('{msg}');</script>", "text/html");
        }

        public List<MenuInfo> GetMenuInfos()
        {
            List<MenuInfo> result = new List<MenuInfo>();
            Queue<string> actionQ = new Queue<string>();
            Assembly ass = Assembly.Load("OA.Web");
            Type[] listType = ass.GetTypes().Where(t => t.IsClass).ToArray();
            foreach (Type t in listType)
            {
                if (t.BaseType == typeof(BaseMemberController))
                {
                    MethodInfo[] listMethod = t.GetMethods();
                    foreach (MethodInfo info in listMethod)
                    {
                        if (info.ReturnType == typeof(IActionResult))
                        {
                            var attribute2 = info.GetCustomAttribute(typeof(MyActionFilterAttribute));
                            if (attribute2 != null)
                            {
                                MyActionFilterAttribute attribute3 = (MyActionFilterAttribute)attribute2;
                                if (actionQ.Contains(attribute3.Key))
                                {
                                    continue;
                                }
                                actionQ.Enqueue(attribute3.Key);
                                MenuInfo menuInfo = new MenuInfo();
                                menuInfo.at = info.Name;
                                string[] temps = t.FullName.Split(new string[] { "." },StringSplitOptions.RemoveEmptyEntries);//OA.Web.Areas.Member.Controllers.BaseMemberController
                                if (temps.Length != 6) continue;
                                menuInfo.a = temps[3];
                                menuInfo.ct = temps[5].Replace("Controller","");
                                menuInfo.c = attribute3.Key;
                                menuInfo.m = attribute3.IsMenu;
                                menuInfo.cn = attribute3.DataIconClass;
                                menuInfo.n = attribute3.Name;
                                menuInfo.p = attribute3.ParentName;
                                result.Add(menuInfo);
                            }
                        }
                    }

                }
            }

            ///002
            var listCustomForm = this.dbContextFactory.DbContext.CustomForm.Include("FormGroup").Where(m => m.Status != -1).Select(m => new { ID = m.ID, FormGroupID = m.FormGroupID, Name = m.Name, GroupID = m.FormGroup.ID, GroupName = m.FormGroup.Name, Ico = m.Ico }).ToList();


            var customGroup = listCustomForm.GroupBy(m => new { m.GroupName, m.GroupID }).ToList();

            foreach (var item in customGroup)
            {
                MenuInfo menuInfo = new MenuInfo();
                menuInfo.a = "Member";
                menuInfo.ct = "CustomForm";
                menuInfo.at = $"Category?id={item.Key.GroupID}";
                menuInfo.m = true;
                menuInfo.c = "002" + item.Key.GroupID.ToString("D3");
                menuInfo.p = "流程审批";
                menuInfo.n = item.Key.GroupName;
                 
                result.Add(menuInfo);

                foreach (var item2 in item)
                {
                    MenuInfo child = new MenuInfo();
                    child.a = "Member";
                    child.ct = "CustomForm";
                    child.at = $"Index?id={item2.ID}";
                    child.m = false;
                    child.c = "002" + item.Key.GroupID.ToString("D3")+item2.ID.ToString("D3");
                    child.p = item.Key.GroupName;
                    child.n = item2.Name;                    
                    result.Add(child);
                }
            }

            foreach (var item in listCustomForm)
            {
                MenuInfo menuInfo = new MenuInfo();
                menuInfo.a = "Member";
                menuInfo.ct = "Statistic";
                menuInfo.at = $"Index?customFormID={item.ID}";                 
                menuInfo.c = "888" + item.ID.ToString("D3");
                menuInfo.p = "查询与统计";
                menuInfo.n = item.Name;
                if(string.IsNullOrWhiteSpace(item.Ico))
                {
                    menuInfo.cn = "iconwenjian";
                }
                else
                {
                    menuInfo.cn = item.Ico;
                }
                
                menuInfo.m = true;
                result.Add(menuInfo);
            }

            return result.OrderBy(m => m.c).ToList();

        }


    }

    
}